package com.example.kotlinlearn.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import com.example.kotlinlearn.BaseActivity
import com.example.kotlinlearn.databinding.ActivityMediaBinding
import com.example.kotlinlearn.databinding.ActivityServiceBinding

class ServiceActivity : BaseActivity() {

    lateinit var binding: ActivityServiceBinding
    lateinit var downloadBinder: MyService.DownloadBinder
    private val connection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            downloadBinder = service as MyService.DownloadBinder
            downloadBinder.startDownload()
            downloadBinder.getProgress()
        }
        override fun onServiceDisconnected(name: ComponentName?) {
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityServiceBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.startService.setOnClickListener {
            val intent = Intent(this,MyService::class.java)
            startService(intent)
        }
        binding.stopService.setOnClickListener {
            val intent = Intent(this,MyService::class.java)
            stopService(intent)
        }
        binding.bindService.setOnClickListener {
            val intent = Intent(this,MyService::class.java)
            bindService(intent,connection,Context.BIND_AUTO_CREATE) //绑定
        }
        binding.unbindService.setOnClickListener {
            unbindService(connection) //解绑
        }
    }
}